import { Navigate, useLocation } from "react-router-dom";
import { type RootState, store } from '../../store/index'
import React from 'react'
import { HOME_URL } from "../../constants";
import { useSelector } from "react-redux";
import { searchRoute } from '../../utils/utils'
import { rootRouter } from '../index'

// 路由守卫组件
const AuthRouter: React.FC<{ children: JSX.Element }> = ({ children }) => {
  const { pathname } = useLocation();
  const { authRouter } = useSelector((state: RootState) => state.auth)
  // 动态设置标题
  const router = searchRoute(pathname, rootRouter)
  const title = import.meta.env.VITE_GLOB_APP_TITLE
  document.title = router?.meta?.title ? `${router.meta.title} - ${title}` : title

  // 判断当前路由是否需要访问权限(不需要权限直接放行)
  if (!router.meta?.requiresAuth) return children

  // 判断token 是否存在，不存在重定向到登录页面
  const token = store.getState().global.token;
  if (!token) return <Navigate to='/login' replace />

  // 动态路由，根据后端返回的菜单数据生成的一维数组
  const dynamicRouter = authRouter;

  // 静态路由
  const staticRouter = [HOME_URL, '/404']
  const routerList = dynamicRouter.concat(staticRouter)

  // 如果访问的地址没有在路由表中重定向到404页面
  if (routerList.indexOf(pathname) === -1) return <Navigate to='/404' />

  // 当前账号有权限返回 Router，正常访问页面
  return children;
}

export default AuthRouter;